import {
  regeneratorRuntime
} from "../../libs/runtime/runtime";
import {
  request
} from "../../request";
//引入第三方表单审核插件
import WxValidate from '../../utils/WxValidate.js'
//formdata存储 上传表单数据
//chooseimgs存储 上传图片数据
//保证上传完图片上传 表单数据
//逻辑麻烦死了 建议别动
//formarr 存储storage数据
var formarr = {}
Page({
  data: {
    //挺蠢的最好这类数据应该与数据库相关 
    array: ['强烈推荐，闭眼冲', '一般推荐，吃不吃都可以', '推荐，值的一试', '踩雷产品，可千万别吃', ],
    index: 0,
    labelarr: ['标记类型内容更清晰', '早餐', '午餐', '晚餐', '小吃', '零食', '糕点'],
    labelIdx: 0,
    chooseImgs: [],
  },
  onLoad(options) { 
    console.log(options)
    this.sX();
    this.initValidate() //验证规则函数
    if (wx.getStorageSync('localformdata')) {
      let localformdata = wx.getStorageSync('localformdata')
      formarr = localformdata
      this.setData({
        ...localformdata
      })
    }
    if(options)
      this.setData({
        ...options
      })
  },
  onShow() {

  },
  //表单提交按钮
  async formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    const params = e.detail.value
    //校验表单数据
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    //将size 塞进去顺便瞅瞅 图片合法性
    if (!this.data.chooseImgs.length) {
      wx.showModal({
        content: '请上传图片',
        showCancel: false,
      })
      return
    }
    const res = await request({
      url: '/main/enjoy',
      method: 'POST',
      data: {
        ...e.detail.value
      }
    });
    console.log(res)
    console.log(res[0].share_id)
    this.setData({
      share_id:res[0].share_id
    })
    let that = this
    wx.getImageInfo({
      src: this.data.chooseImgs[0],
      success(res) {
        console.log(res.width)
        console.log(res.height)
        let size = res.width / res.height
        if (size >= 0.75 && size < 1) {
          size = '4-3'
        } else if (size === 1) {
          size = '1-1'
        } else {
          size = '16-9'
        }
        console.log(size)
        that.ImgUpload(that.data.chooseImgs, 0, that.data.chooseImgs.length, that.data.share_id,size)
      }
    })
  },
  //递归上传图片
  ImgUpload(chooseImgs,index,length,share_id,size) {
    let that = this
    wx.uploadFile({
      url: 'https://fourgoldhua.cn/main/upload',
      filePath: chooseImgs[index],
      name: 'file',
      header: {
        'accept': 'application/json',
        'token': `${wx.getStorageSync('openid')}`,
        'id': `${share_id}`,
        "index": `${index++}`,
        'size': `${size}`
      },
      formData: {
        test: '1'
      },
      success: function (res) {
        console.log(index)
        console.log(res)
        if (res.statusCode == 200 && index == chooseImgs.length) {
          console.log("上传成功")
          wx.showToast({
            title: '上传成功',
          })
          wx.clearStorageSync('localformdata')
          wx.switchTab({
            url: '/pages/home/home',
          })
        } else if (res.statusCode !== 200 && index == chooseImgs.length) {
          wx.showToast({
            title: '上传失败',
          })
        }
        that.ImgUpload(chooseImgs, index, length, share_id,size)
      }
    })
  },
  //表单值改变
  changeInput(e) {
    let prop = e.currentTarget.dataset.prop
    formarr[prop] = e.detail.value;
  },
  //表单保存
  SaveFormdata() {
    wx.setStorageSync('localformdata', formarr)
  },
  //表单报错提示 
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //表单验证函数
  initValidate() {
    const rules = {
      title: {
        required: true,
        maxlength: 15
      },
      tags: {
        required: true,
      },
      text: {
        required: true,
      },
      food: {
        required: true,
      },
      top: {
        required: true,
      },
      addr:{
        required: true,
      }
    }
    const messages = {
      title: {
        required: '请输入文章标题',
      },
      tags: {
        required: '请输入标签',
      },
      text: {
        required: '请输入正文',
      },
      food: {
        required: '请选择美食类型',
      },
      top: {
        required: '请选择推荐指数',
      },
      addr:{
        required: '请输入地点',
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  //点击加号选择图片
  handleChooseImg() {
    wx.chooseImage({
      count: 6,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {
        console.log(result)
        this.setData({
          //图片数组拼接
          chooseImgs: [...this.data.chooseImgs, ...result.tempFilePaths]
        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  //点击图片删除
  handleRemoveImg(e) {
    const {
      index
    } = e.currentTarget.dataset;
    console.log(index);
    let {
      chooseImgs
    } = this.data
    chooseImgs.splice(index, 1);
    this.setData({
      chooseImgs
    })
  },
  //上传地址经纬度
  onChangeAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          chooseAddress: res.name,
          choosejwd: res.latitude + ',' + res.longitude,
        });
        formarr['choosejwd'] = res.latitude + ',' + res.longitude;
        formarr['chooseAddress'] = res.name;
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
  //picker改变
  bindPickerChangefood(e) {
    console.log(this.data.labelarr[e.detail.value])
    this.setData({
      labelIdx: e.detail.value
    });
    formarr['labelIdx'] = e.detail.value
  },
  //picker改变
  bindPickerChangerecommend(e) {
    console.log(this.data.array[e.detail.value])
    this.setData({
      index: e.detail.value
    });
    formarr['index'] = e.detail.value
  },
  async sX() {
    const res = await request({
      url: '/shuju/sx',
    });
    if (res.data === 1) {
      this.setData({
        ondisplay: 'block'
      })
    }
  },
  jumpto_search_page: function (e) {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
})